<template>
  <div id="container"></div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import axios from "axios";
export default {
  props: ['driver_id'],
  name: "MapContainer",
  mounted() {
    // 组件挂载后初始化地图和获取司机位置
    this.initAMap();
    this.getDriverPosition(this.driver_id);
    this.$bus.$on('test', (startPoint, endPoint) => {
      this.mapStart = startPoint;
      this.mapEnd = endPoint;
      console.log(startPoint);
      console.log(endPoint);
      this.addMarkers();
      this.planRoads();

    });
  },

  data() {
    return {
      driverPosition: [], // 存储司机位置
      mapStart: [],//起点经纬度数组
      mapEnd: [],//终点经纬度数组
      map: null,
      roads: [],//存储规划的所有路线
      waypoints: []//途经点
    };
  },
  methods: {
    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "5aabd76db61a2972cf06e6fdb228a6f4",
      };
      AMapLoader.load({
        key: "24476c88646fc730e96da725bf1822c3",
        version: "2.0",
        plugins: ["AMap.Driving"],
      })
        .then((AMap) => {
          this.map = new AMap.Map("container", {
            viewMode: "3D",
            zoom: 11,
            center: [118.241067, 24.421036],
          });
          
          
        })
        .catch((e) => {
          console.log(e);
        });
    },
    addCustomMarker() {
      // 创建点标记并添加到地图上
      if (this.map && this.driverPosition && this.driverPosition.lng && this.driverPosition.lat) {
        const marker = new AMap.Marker({
          position: new AMap.LngLat(this.driverPosition.lng, this.driverPosition.lat),
          anchor: "center",
          icon: require('@/assets/图示司机位置.png'),

        });
        this.map.add(marker);
      }
    },
    getDriverPosition(driverId) {
      // 根据司机 ID 获取位置信息
      console.log(driverId);
      axios.post('/pub/ai/driver_locations', {
        driver_ids: [driverId]
      }, {
        headers: {
          "user-token": "12306070809_" + "6ac2ce7d291b4dffa9053edc6650ce9b",
        },
      })
        .then(response => {
          this.driverPosition = response.data.result[0];
          console.log(this.driverPosition);
          this.addCustomMarker();
        })
        .catch(err => {
          console.error(err);
        });
    },
    addMarkers() {
      const markers = [];
      if (this.mapStart && this.mapEnd && this.map) {
        this.mapStart.forEach((startPoint, index) => {
          const marker = new AMap.Marker({
            position: new AMap.LngLat(startPoint.lng, startPoint.lat),
            offset: new AMap.Pixel(-18, -32),
            icon: require(`@/assets/p${index + 1}.png`),
            zIndex: 20, // 设置较高的 zIndex 值

          });
          markers.push(marker);
          this.map.add(markers);
        });
        this.mapEnd.forEach((endPoint, index) => {
          const marker1 = new AMap.Marker({
            position: new AMap.LngLat(endPoint.lng, endPoint.lat),
            offset: new AMap.Pixel(-18, -32),
            icon: require(`@/assets/A${index + 1}.png`),
            zIndex: 20
          });
          markers.push(marker1);
          this.map.add(markers);
        });
      }
    },
    planRoads() {
      if (this.map && this.mapStart && this.mapEnd) {
        const driving = new AMap.Driving({
          map: this.map,
        });

        // 确保起点和终点不是同一个点
        if (this.mapStart[0].lat === this.mapEnd[this.mapEnd.length - 1].lat && this.mapStart[0].lng === this.mapEnd[this.mapEnd.length - 1].lng) {
          console.error("起点和终点不能是同一个点");
          return;
        }

        // 创建途经点数组，不包括起点和终点
        let waypoints = [];
        for (let i = 1; i < this.mapStart.length; i++) {
          waypoints.push(new AMap.LngLat(this.mapStart[i].lng, this.mapStart[i].lat));
        }
        for (let i = 0; i < this.mapEnd.length - 1; i++) {
          waypoints.push(new AMap.LngLat(this.mapEnd[i].lng, this.mapEnd[i].lat));
        }

        // 使用 AMap.Driving 进行路线规划，包含途经点
        driving.search(
          new AMap.LngLat(this.mapStart[0].lng, this.mapStart[0].lat), // 起点
          new AMap.LngLat(this.mapEnd[this.mapEnd.length - 1].lng, this.mapEnd[this.mapEnd.length - 1].lat), // 终点
          {
            waypoints: waypoints, // 途经点数组
          },
          (status, result) => {
            if (status === "complete" && result.info === "OK") {
              this.roads = result.routes; // 将路线结果保存到 this.roads
              //console.log("路线规划完成", result.routes[0].steps);
              //console.log(waypoints);



            } else {
              console.error("路线规划失败：", status);
            }
          }
        );
      }
    },
  },
};
</script>

<style scoped>
#container {
  width: 100%;
  height: 100%;
}
</style>